<template>
  <div class="account-container" v-loading="loading">
    <el-row :gutter="20">
      <!-- 左侧信息卡片 -->
      <el-col :span="8">
        <el-card class="info-card">
          <div class="merchant-info">
            <div class="avatar-container">
              <el-avatar :size="100" :src="merchantInfo.avatar" />
              <el-upload
                class="avatar-uploader"
                action="/api/upload"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <el-button type="primary" link>更换头像</el-button>
              </el-upload>
            </div>
            <div class="merchant-name">{{ merchantInfo.name || '洗护专家店铺' }}</div>
            <div class="merchant-type">{{ merchantInfo.type || '企业商户' }}</div>
            <div class="merchant-status">
              <el-tag :type="merchantInfo.status === '已认证' ? 'success' : 'warning'">
                {{ merchantInfo.status || '待认证' }}
              </el-tag>
            </div>
            <div class="merchant-meta">
              <div class="meta-item">
                <el-icon><Calendar /></el-icon>
                <span>入驻时间：{{ merchantInfo.joinTime || '2023-01-15' }}</span>
              </div>
              <div class="meta-item">
                <el-icon><Location /></el-icon>
                <span>店铺地址：{{ merchantInfo.address || '北京市朝阳区建国路88号' }}</span>
              </div>
              <div class="meta-item">
                <el-icon><Star /></el-icon>
                <span>信用分数：{{ merchantInfo.creditScore || 0 }}分</span>
              </div>
              <div class="meta-item">
                <el-icon><Document /></el-icon>
                <span>营业执照：{{ merchantInfo.businessLicense || '已上传' }}</span>
              </div>
              <div class="meta-item">
                <el-icon><User /></el-icon>
                <span>法人代表：{{ merchantInfo.legalPerson || '张三' }}</span>
              </div>
              <div class="meta-item">
                <el-icon><Phone /></el-icon>
                <span>联系电话：{{ maskPhone(merchantInfo.phone) }}</span>
              </div>
              <div class="meta-item">
                <el-icon><Message /></el-icon>
                <span>邮箱地址：{{ maskEmail(merchantInfo.email) }}</span>
              </div>
              <div class="meta-item">
                <el-icon><Clock /></el-icon>
                <span>最后登录：{{ merchantInfo.lastLoginTime || '2024-12-21 10:30:00' }}</span>
              </div>
            </div>

            <!-- 服务类型展示 -->
            <div class="service-types">
              <div class="service-title">提供服务</div>
              <div class="service-tags">
                <el-tag
                  v-for="service in merchantInfo.serviceTypes"
                  :key="service"
                  type="primary"
                  size="small"
                  class="service-tag"
                >
                  {{ service }}
                </el-tag>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 账户安全 -->
        <el-card class="security-card">
          <template #header>
            <div class="card-header">
              <span>安全设置</span>
              <el-tag type="success" size="small">安全等级：高</el-tag>
            </div>
          </template>
          <div class="security-list">
            <div class="security-item">
              <div class="item-info">
                <el-icon><Lock /></el-icon>
                <div class="item-details">
                  <span class="item-label">登录密码</span>
                  <span class="item-status">已设置</span>
                </div>
              </div>
              <el-button type="primary" link @click="handleChangePassword">
                修改
              </el-button>
            </div>
            <div class="security-item">
              <div class="item-info">
                <el-icon><Phone /></el-icon>
                <div class="item-details">
                  <span class="item-label">手机号</span>
                  <span class="item-value">{{ maskPhone(merchantInfo.phone) }}</span>
                </div>
              </div>
              <el-button type="primary" link @click="handleChangePhone">
                修改
              </el-button>
            </div>
            <div class="security-item">
              <div class="item-info">
                <el-icon><Message /></el-icon>
                <div class="item-details">
                  <span class="item-label">邮箱</span>
                  <span class="item-value">{{ maskEmail(merchantInfo.email) }}</span>
                </div>
              </div>
              <el-button type="primary" link @click="handleChangeEmail">
                修改
              </el-button>
            </div>
          </div>
        </el-card>

        <!-- 银行卡管理 -->
        <el-card class="bank-card">
          <template #header>
            <div class="card-header">
              <span>银行卡管理</span>
              <el-button type="primary" link @click="handleAddBankCard">
                添加银行卡
              </el-button>
            </div>
          </template>
          <div class="bank-list">
            <div v-if="merchantInfo.bankCards && merchantInfo.bankCards.length > 0" class="bank-cards">
              <div
                v-for="(card, index) in merchantInfo.bankCards"
                :key="index"
                class="bank-card-item"
                :class="{ 'default-card': card.isDefault }"
              >
                <div class="card-info">
                  <div class="card-icon">
                    <el-icon><CreditCard /></el-icon>
                  </div>
                  <div class="card-details">
                    <div class="card-number">{{ maskBankCard(card.cardNumber) }}</div>
                    <div class="card-bank">{{ card.bankName }}</div>
                    <div class="card-holder">持卡人：{{ card.holderName || '张三' }}</div>
                    <div class="card-type">{{ card.cardType }}</div>
                  </div>
                  <div class="card-status">
                    <el-tag v-if="card.isDefault" type="success" size="small">默认</el-tag>
                    <el-tag v-if="card.status === 'verified'" type="success" size="small">已验证</el-tag>
                  </div>
                </div>
                <div class="card-actions">
                  <el-button
                    v-if="!card.isDefault"
                    type="primary"
                    link
                    size="small"
                    @click="handleSetDefaultCard(card.id)"
                  >
                    设为默认
                  </el-button>
                  <el-button
                    type="danger"
                    link
                    size="small"
                    @click="handleRemoveBankCard(card.id)"
                  >
                    解绑
                  </el-button>
                </div>
              </div>
            </div>
            <div v-else class="no-bank-cards">
              <el-empty description="暂未绑定银行卡">
                <el-button type="primary" @click="handleAddBankCard">
                  立即绑定
                </el-button>
              </el-empty>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧认证信息 -->
      <el-col :span="16">
        <!-- 商家资质信息 -->
        <el-card class="qualification-card">
          <template #header>
            <div class="card-header">
              <span>商家资质信息</span>
              <el-tag type="success" size="small">已认证</el-tag>
            </div>
          </template>
          <div class="qualification-info">
            <el-row :gutter="20">
              <el-col :span="12">
                <div class="info-item">
                  <span class="label">店铺名称：</span>
                  <span class="value">{{ merchantInfo.shopName || '洗护专家店铺' }}</span>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="info-item">
                  <span class="label">店铺类型：</span>
                  <span class="value">企业商户</span>
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <div class="info-item">
                  <span class="label">执照编号：</span>
                  <span class="value">{{ merchantInfo.licenseNo || '91110000123456789X' }}</span>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="info-item">
                  <span class="label">法人代表：</span>
                  <span class="value">{{ merchantInfo.legalPerson || '张三' }}</span>
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <div class="info-item">
                  <span class="label">成立日期：</span>
                  <span class="value">{{ merchantInfo.establishDate || '2020-01-15' }}</span>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="info-item">
                  <span class="label">营业期限：</span>
                  <span class="value">{{ merchantInfo.businessTermStart || '2020-01-15' }} 至 {{ merchantInfo.businessTermEnd || '2040-01-15' }}</span>
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <div class="info-item">
                  <span class="label">服务类型：</span>
                  <div class="service-types-display">
                    <el-tag
                      v-for="service in merchantInfo.serviceTypes"
                      :key="service"
                      type="primary"
                      size="small"
                      class="service-tag"
                    >
                      {{ service }}
                    </el-tag>
                  </div>
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <div class="info-item">
                  <span class="label">店铺地址：</span>
                  <span class="value">{{ merchantInfo.fullAddress || '北京市朝阳区建国路88号SOHO现代城A座1001室' }}</span>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>

        <el-card class="certification-card">
          <template #header>
            <div class="card-header">
              <span>认证管理</span>
              <div class="header-actions">
                <el-button
                  v-if="merchantInfo.status !== '已认证'"
                  type="primary"
                  @click="handleSubmitCertification"
                >
                  提交认证
                </el-button>
                <el-button
                  v-if="merchantInfo.status === '已认证'"
                  type="primary"
                  link
                  @click="handleViewCertification"
                >
                  查看认证信息
                </el-button>
              </div>
            </div>
          </template>

          <el-form
            ref="certificationForm"
            :model="certificationForm"
            :rules="certificationRules"
            label-width="120px"
            class="certification-form"
          >
            <!-- 基本信息 -->
            <div class="form-section">
              <div class="section-title">
                <el-icon><User /></el-icon>
                <span>基本信息</span>
              </div>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="店铺名称" prop="shopName">
                    <el-input v-model="certificationForm.shopName" placeholder="请输入店铺名称" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="店铺类型" prop="shopType">
                    <el-select v-model="certificationForm.shopType" style="width: 100%" placeholder="请选择店铺类型">
                      <el-option label="个人店铺" value="personal" />
                      <el-option label="企业店铺" value="enterprise" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="联系人" prop="contactName">
                    <el-input v-model="certificationForm.contactName" placeholder="请输入联系人姓名" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="联系电话" prop="contactPhone">
                    <el-input v-model="certificationForm.contactPhone" placeholder="请输入联系电话" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item label="店铺地址" prop="address">
                <el-cascader
                  v-model="certificationForm.region"
                  :options="regionOptions"
                  style="width: 100%"
                  placeholder="请选择所在地区"
                />
                <el-input
                  v-model="certificationForm.address"
                  class="mt-2"
                  placeholder="请输入详细地址"
                />
              </el-form-item>
            </div>

            <!-- 营业执照信息 -->
            <div class="form-section">
              <div class="section-title">
                <el-icon><Document /></el-icon>
                <span>营业执照信息</span>
              </div>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="营业执照号" prop="licenseNo">
                    <el-input v-model="certificationForm.licenseNo" placeholder="请输入营业执照号" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="法定代表人" prop="legalPerson">
                    <el-input v-model="certificationForm.legalPerson" placeholder="请输入法定代表人姓名" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="成立日期" prop="establishDate">
                    <el-date-picker
                      v-model="certificationForm.establishDate"
                      type="date"
                      style="width: 100%"
                      placeholder="请选择成立日期"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="营业期限" prop="businessTerm">
                    <el-date-picker
                      v-model="certificationForm.businessTerm"
                      type="daterange"
                      style="width: 100%"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item label="洗护服务类型" prop="serviceTypes">
                <el-checkbox-group v-model="certificationForm.serviceTypes">
                  <el-checkbox label="洗衣服">洗衣服</el-checkbox>
                  <el-checkbox label="洗鞋">洗鞋</el-checkbox>
                  <el-checkbox label="洗萌宠">洗萌宠</el-checkbox>
                  <el-checkbox label="洗包包">洗包包</el-checkbox>
                  <el-checkbox label="洗被子">洗被子</el-checkbox>
                  <el-checkbox label="洗车">洗车</el-checkbox>
                  <el-checkbox label="上门清洗">上门清洗</el-checkbox>
                  <el-checkbox label="疏通厕所">疏通厕所</el-checkbox>
                </el-checkbox-group>
              </el-form-item>

              <el-form-item label="其他经营范围" prop="businessScope">
                <el-input
                  v-model="certificationForm.businessScope"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入其他经营范围（可选）"
                />
              </el-form-item>
            </div>

            <!-- 证件上传 -->
            <div class="form-section">
              <div class="section-title">
                <el-icon><Upload /></el-icon>
                <span>证件上传</span>
              </div>
              <div class="upload-tips">
                <el-alert
                  title="请上传清晰的证件照片，支持jpg、png格式，单个文件不超过5MB"
                  type="info"
                  :closable="false"
                  show-icon
                />
              </div>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="营业执照信息">
                    <div class="license-display">
                      <div class="license-info">
                        <div class="info-row">
                          <div class="info-item">
                            <span class="label">执照编号：</span>
                            <span class="value">{{ certificationForm.licenseNo }}</span>
                          </div>
                          <div class="info-item">
                            <span class="label">法人代表：</span>
                            <span class="value">{{ certificationForm.legalPerson }}</span>
                          </div>
                        </div>
                        <div class="info-row">
                          <div class="info-item">
                            <span class="label">成立日期：</span>
                            <span class="value">{{ certificationForm.establishDate }}</span>
                          </div>
                          <div class="info-item">
                            <span class="label">营业期限：</span>
                            <span class="value">{{ certificationForm.businessTerm[0] }} 至 {{ certificationForm.businessTerm[1] }}</span>
                          </div>
                        </div>
                      </div>
                      <div class="license-image-display">
                        <img :src="certificationForm.licenseImage" alt="营业执照" class="license-preview" />
                        <div class="image-status">
                          <el-tag type="success" size="small">已认证</el-tag>
                        </div>
                      </div>
                    </div>
                    <div class="certification-note">
                      <el-icon><InfoFilled /></el-icon>
                      <span>营业执照信息已通过平台审核认证，如需修改请联系客服</span>
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="法人身份证" prop="idCardImage">
                    <el-upload
                      class="certification-uploader"
                      action="/api/upload"
                      :show-file-list="false"
                      :on-success="(res) => handleUploadSuccess(res, 'idCardImage')"
                      :before-upload="beforeUpload"
                      :headers="uploadHeaders"
                    >
                      <div class="upload-content">
                        <img
                          v-if="certificationForm.idCardImage"
                          :src="certificationForm.idCardImage"
                          class="uploaded-image"
                        />
                        <template v-else>
                          <el-icon class="uploader-icon"><Plus /></el-icon>
                          <div class="upload-tip">点击上传法人身份证</div>
                          <div class="upload-desc">支持jpg、png格式，不超过5MB</div>
                        </template>
                      </div>
                    </el-upload>
                  </el-form-item>
                </el-col>
              </el-row>
              <!-- 退店申请 -->
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="退店申请">
                    <div class="quit-store-section">
                      <div class="quit-info">
                        <el-icon class="warning-icon"><WarningFilled /></el-icon>
                        <div class="quit-content">
                          <h4>申请退店</h4>
                          <p>退店后将无法继续接收订单，已完成订单的资金将在结算期后正常到账</p>
                          <ul class="quit-conditions">
                            <li>确保所有订单已完成或妥善处理</li>
                            <li>清理完成所有待结算资金</li>
                            <li>处理完成所有客户投诉和纠纷</li>
                            <li>退店申请提交后需要3-5个工作日审核</li>
                          </ul>
                        </div>
                      </div>
                      <div class="quit-actions">
                        <el-button type="danger" @click="showQuitStoreDialog">
                          申请退店
                        </el-button>
                      </div>
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>

            <!-- 认证状态 -->
            <div v-if="merchantInfo.status === '已认证'" class="certification-status">
              <el-result
                icon="success"
                title="认证成功"
                :sub-title="merchantInfo.certificationTime"
              >
                <template #extra>
                  <el-button type="primary" @click="handleViewCertification">
                    查看认证信息
                  </el-button>
                </template>
              </el-result>
            </div>
          </el-form>
        </el-card>
      </el-col>
    </el-row>

    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="passwordDialogVisible"
      title="修改密码"
      width="400px"
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input
            v-model="passwordForm.oldPassword"
            type="password"
            show-password
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="passwordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUpdatePassword">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 退店申请对话框 -->
    <el-dialog
      v-model="quitStoreDialogVisible"
      title="退店申请"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="quit-dialog-content">
        <div class="quit-warning">
          <el-icon class="warning-icon"><WarningFilled /></el-icon>
          <h3>请仔细阅读退店须知</h3>
        </div>

        <div class="quit-checklist">
          <h4>退店前请确认以下事项：</h4>
          <el-checkbox-group v-model="quitChecklist">
            <div class="checklist-item">
              <el-checkbox label="orders">所有订单已完成或妥善处理</el-checkbox>
            </div>
            <div class="checklist-item">
              <el-checkbox label="finance">已清理完成所有待结算资金</el-checkbox>
            </div>
            <div class="checklist-item">
              <el-checkbox label="complaints">已处理完成所有客户投诉和纠纷</el-checkbox>
            </div>
            <div class="checklist-item">
              <el-checkbox label="understand">理解退店后无法恢复，需重新注册</el-checkbox>
            </div>
          </el-checkbox-group>
        </div>

        <el-form
          ref="quitFormRef"
          :model="quitForm"
          :rules="quitRules"
          label-width="100px"
        >
          <el-form-item label="退店原因" prop="reason">
            <el-select v-model="quitForm.reason" placeholder="请选择退店原因" style="width: 100%;">
              <el-option label="业务调整" value="business_adjustment" />
              <el-option label="经营困难" value="business_difficulty" />
              <el-option label="服务区域变更" value="area_change" />
              <el-option label="平台政策不符" value="policy_mismatch" />
              <el-option label="其他原因" value="other" />
            </el-select>
          </el-form-item>

          <el-form-item label="详细说明" prop="description">
            <el-input
              v-model="quitForm.description"
              type="textarea"
              placeholder="请详细说明退店原因，以便我们改进服务"
              :rows="4"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="联系方式" prop="contact">
            <el-input
              v-model="quitForm.contact"
              placeholder="请留下联系方式，便于后续沟通"
            />
          </el-form-item>
        </el-form>

        <div class="quit-notice">
          <el-alert
            title="重要提醒"
            type="warning"
            :closable="false"
            show-icon
          >
            <template #default>
              <p>1. 退店申请提交后，将在3-5个工作日内完成审核</p>
              <p>2. 审核期间您仍可正常使用平台功能</p>
              <p>3. 退店成功后，所有数据将被清除且无法恢复</p>
              <p>4. 已完成订单的资金将按正常结算周期到账</p>
            </template>
          </el-alert>
        </div>
      </div>

      <template #footer>
        <el-button @click="quitStoreDialogVisible = false">取消</el-button>
        <el-button
          type="danger"
          :disabled="!isQuitFormValid"
          :loading="quitSubmitting"
          @click="submitQuitApplication"
        >
          确认提交退店申请
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import {
  Calendar,
  Location,
  Lock,
  Phone,
  Message,
  Plus,
  User,
  Document,
  Upload,
  InfoFilled,
  WarningFilled,
  Star,
  CreditCard
} from '@element-plus/icons-vue'
import {
  getMerchantInfo,
  updateMerchantInfo,
  updateMerchantPassword,
  submitMerchantCertification
} from '@/api/account'
import {
  checkClosureConditions,
  submitClosureApplication
} from '@/api/store-closure'

// 商家信息
const merchantInfo = reactive({
  avatar: '',
  name: '',
  type: '',
  status: '',
  joinTime: '',
  address: '',
  phone: '',
  email: '',
  certificationTime: '',
  serviceTypes: [],
  creditScore: 0,
  businessLicense: '',
  legalPerson: '',
  shopName: '',
  licenseNo: '',
  establishDate: '',
  businessTermStart: '',
  businessTermEnd: '',
  fullAddress: '',
  bankCards: []
})

// 认证表单
const certificationForm = reactive({
  shopName: '',
  shopType: '',
  contactName: '',
  contactPhone: '',
  region: [],
  address: '',
  licenseNo: '',
  legalPerson: '',
  establishDate: '',
  businessTerm: [],
  serviceTypes: [],
  businessScope: '',
  licenseImage: '',
  idCardImage: '',
  otherCertificates: ''
})

// 表单验证规则
const certificationRules = {
  shopName: [
    { required: true, message: '请输入店铺名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  shopType: [
    { required: true, message: '请选择店铺类型', trigger: 'change' }
  ],
  contactName: [
    { required: true, message: '请输入联系人', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入详细地址', trigger: 'blur' }
  ],
  licenseNo: [
    { required: true, message: '请输入营业执照号', trigger: 'blur' }
  ],
  legalPerson: [
    { required: true, message: '请输入法定代表人', trigger: 'blur' }
  ],
  establishDate: [
    { required: true, message: '请选择成立日期', trigger: 'change' }
  ],
  businessTerm: [
    { required: true, message: '请选择营业期限', trigger: 'change' }
  ],
  businessScope: [
    { required: true, message: '请输入经营范围', trigger: 'blur' }
  ],
  licenseImage: [
    { required: true, message: '请上传营业执照', trigger: 'change' }
  ],
  idCardImage: [
    { required: true, message: '请上传法人身份证', trigger: 'change' }
  ]
}

// 密码修改
const passwordDialogVisible = ref(false)
const passwordFormRef = ref(null)
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 退店申请
const quitStoreDialogVisible = ref(false)
const quitFormRef = ref(null)
const quitSubmitting = ref(false)
const quitChecklist = ref([])
const quitForm = reactive({
  reason: '',
  description: '',
  contact: ''
})

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 退店表单验证规则
const quitRules = {
  reason: [
    { required: true, message: '请选择退店原因', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请详细说明退店原因', trigger: 'blur' },
    { min: 10, message: '说明内容至少10个字符', trigger: 'blur' }
  ],
  contact: [
    { required: true, message: '请留下联系方式', trigger: 'blur' }
  ]
}

// 加载状态
const loading = ref(false)

// 获取商家信息
const fetchMerchantInfo = async () => {
  loading.value = true
  try {
    const response = await getMerchantInfo()
    if (response.code === 200) {
      Object.assign(merchantInfo, response.data)
      if (response.data.certification) {
        Object.assign(certificationForm, response.data.certification)
      }
      console.log('✅ 商家信息加载成功')
    } else {
      throw new Error(response.message || '获取商家信息失败')
    }
  } catch (error) {
    console.error('❌ 获取商家信息失败:', error)
    ElMessage.error(error.message || '获取商家信息失败')
  } finally {
    loading.value = false
  }
}

// 头像上传
const handleAvatarSuccess = async (res) => {
  try {
    merchantInfo.avatar = res.url
    const response = await updateMerchantInfo({ avatar: res.url })
    if (response.code === 200) {
      ElMessage.success('头像更新成功')
    } else {
      throw new Error(response.message || '头像更新失败')
    }
  } catch (error) {
    console.error('头像更新失败:', error)
    ElMessage.error(error.message || '头像更新失败')
  }
}

const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('上传头像图片只能是图片格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
  }
  return isImage && isLt2M
}

// 证件上传
const handleUploadSuccess = (res, field) => {
  certificationForm[field] = res.url
}

const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片格式!')
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
  }
  return isImage && isLt5M
}

// 提交认证
const handleSubmitCertification = async () => {
  try {
    const response = await submitMerchantCertification(certificationForm)
    if (response.code === 200) {
      ElMessage.success('提交成功，请等待审核')
      await fetchMerchantInfo()
    } else {
      throw new Error(response.message || '提交认证失败')
    }
  } catch (error) {
    console.error('提交认证失败:', error)
    ElMessage.error(error.message || '提交认证失败')
  }
}

// 修改密码
const handleChangePassword = () => {
  passwordDialogVisible.value = true
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
}

const handleUpdatePassword = async () => {
  if (!passwordFormRef.value) return

  try {
    await passwordFormRef.value.validate()
    const response = await updateMerchantPassword(passwordForm)
    if (response.code === 200) {
      ElMessage.success('密码修改成功')
      passwordDialogVisible.value = false
      // 重置表单
      passwordForm.oldPassword = ''
      passwordForm.newPassword = ''
      passwordForm.confirmPassword = ''
    } else {
      throw new Error(response.message || '密码修改失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('修改密码失败:', error)
      ElMessage.error(error.message || '修改密码失败')
    }
  }
}

// 手机号脱敏
const maskPhone = (phone) => {
  return phone ? phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2') : ''
}

// 邮箱脱敏
const maskEmail = (email) => {
  if (!email) return ''
  const [name, domain] = email.split('@')
  return `${name.charAt(0)}***@${domain}`
}

// 银行卡号脱敏
const maskBankCard = (cardNumber) => {
  if (!cardNumber) return ''
  return cardNumber.replace(/(\d{4})\d{8}(\d{4})/, '$1 **** **** $2')
}

// 银行卡管理相关方法
const handleAddBankCard = () => {
  ElMessage.info('银行卡绑定功能开发中...')
}

const handleSetDefaultCard = (cardId) => {
  ElMessage.success('已设为默认银行卡')
}

const handleRemoveBankCard = (cardId) => {
  ElMessageBox.confirm(
    '确认解绑此银行卡？解绑后将无法使用此卡进行提现。',
    '确认解绑',
    {
      confirmButtonText: '确认解绑',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    ElMessage.success('银行卡已解绑')
  }).catch(() => {
    // 用户取消
  })
}

// 安全设置相关方法
const handleSecuritySettings = () => {
  ElMessage.info('安全设置功能开发中...')
}

const handleChangePhone = () => {
  ElMessage.info('手机号修改功能开发中...')
}

const handleChangeEmail = () => {
  ElMessage.info('邮箱修改功能开发中...')
}

const handleViewCertification = () => {
  ElMessage.info('查看认证信息功能开发中...')
}

// 显示退店对话框 - 先检查退店条件
const showQuitStoreDialog = async () => {
  try {
    // 显示加载状态
    const loadingInstance = ElLoading.service({
      lock: true,
      text: '正在检查退店条件...',
      background: 'rgba(0, 0, 0, 0.7)'
    })

    // 检查退店条件
    const response = await checkClosureConditions()
    loadingInstance.close()

    if (response.code === 200) {
      const { canApplyForClosure, conditions } = response.data

      if (canApplyForClosure) {
        // 满足条件，直接显示申请表单
        quitStoreDialogVisible.value = true
        quitChecklist.value = []
        quitForm.reason = ''
        quitForm.description = ''
        quitForm.contact = merchantInfo.phone
      } else {
        // 不满足条件，显示条件检查结果
        showConditionsCheckResult(conditions)
      }
    } else {
      throw new Error(response.message || '检查退店条件失败')
    }
  } catch (error) {
    console.error('检查退店条件失败:', error)
    ElMessage.error(error.message || '检查退店条件失败')
  }
}

// 显示条件检查结果
const showConditionsCheckResult = (conditions) => {
  const failedConditions = []

  Object.entries(conditions).forEach(([key, condition]) => {
    if (!condition.passed) {
      failedConditions.push(condition.description + ': ' + condition.details)
    }
  })

  ElMessageBox.alert(
    `<div style="text-align: left;">
      <p style="margin-bottom: 15px; color: #f56c6c; font-weight: bold;">
        <i class="el-icon-warning" style="margin-right: 5px;"></i>
        暂不满足退店条件
      </p>
      <p style="margin-bottom: 10px;">请先处理以下问题：</p>
      <ul style="margin: 0; padding-left: 20px; line-height: 1.6;">
        ${failedConditions.map(condition => `<li style="margin-bottom: 5px;">${condition}</li>`).join('')}
      </ul>
      <p style="margin-top: 15px; color: #909399; font-size: 13px;">
        处理完成后可重新申请退店
      </p>
    </div>`,
    '退店条件检查',
    {
      confirmButtonText: '我知道了',
      dangerouslyUseHTMLString: true,
      type: 'warning'
    }
  )
}

// 检查退店表单是否有效
const isQuitFormValid = computed(() => {
  return quitChecklist.value.length === 4 &&
         quitForm.reason &&
         quitForm.description &&
         quitForm.contact
})

// 提交退店申请
const submitQuitApplication = async () => {
  if (!quitFormRef.value) return

  try {
    await quitFormRef.value.validate()

    await ElMessageBox.confirm(
      '确认提交退店申请？提交后将无法撤销，请慎重考虑。',
      '最终确认',
      {
        confirmButtonText: '确认提交',
        cancelButtonText: '再考虑一下',
        type: 'warning'
      }
    )

    quitSubmitting.value = true

    // 提交退店申请到后端
    const response = await submitClosureApplication({
      reason: quitForm.reason,
      description: quitForm.description,
      contactPhone: quitForm.contact,
      emergencyContact: quitForm.contact,
      checklist: quitChecklist.value
    })

    if (response.code === 200) {
      ElMessage.success('退店申请已提交，我们将在3-5个工作日内完成审核')
      quitStoreDialogVisible.value = false

      // 重置表单
      quitChecklist.value = []
      quitForm.reason = ''
      quitForm.description = ''
      quitForm.contact = ''
    } else {
      throw new Error(response.message || '提交退店申请失败')
    }

  } catch (error) {
    if (error !== 'cancel') {
      console.error('提交退店申请失败:', error)
      ElMessage.error(error.message || '提交退店申请失败')
    }
  } finally {
    quitSubmitting.value = false
  }
}

// 上传相关
const uploadHeaders = {
  Authorization: 'Bearer ' + localStorage.getItem('token')
}

// 初始化
onMounted(() => {
  fetchMerchantInfo()
})
</script>

<style scoped>
.account-container {
  padding: 20px;
}

.info-card {
  margin-bottom: 20px;
  
  .merchant-info {
    text-align: center;
    
    .avatar-container {
      margin-bottom: 16px;
      
      .avatar-uploader {
        margin-top: 8px;
      }
    }
    
    .merchant-name {
      font-size: 20px;
      font-weight: bold;
      color: #303133;
      margin-bottom: 8px;
    }
    
    .merchant-type {
      font-size: 14px;
      color: #606266;
      margin-bottom: 8px;
    }
    
    .merchant-status {
      margin-bottom: 16px;
    }
    
    .merchant-meta {
      .meta-item {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        margin-bottom: 8px;
        color: #606266;

        .el-icon {
          font-size: 16px;
        }
      }
    }

    .service-types {
      margin-top: 20px;
      padding-top: 20px;
      border-top: 1px solid #f0f0f0;

      .service-title {
        font-size: 14px;
        color: #333;
        margin-bottom: 10px;
        font-weight: 500;
        text-align: center;
      }

      .service-tags {
        display: flex;
        flex-wrap: wrap;
        justify-content: center;
        gap: 8px;

        .service-tag {
          margin: 0;
        }
      }
    }
  }
}

.security-card {
  .security-list {
    .security-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 0;
      border-bottom: 1px solid #ebeef5;
      
      &:last-child {
        border-bottom: none;
      }
      
      .item-info {
        display: flex;
        align-items: center;
        gap: 8px;
        
        .el-icon {
          font-size: 18px;
          color: #909399;
        }
        
        .item-value {
          color: #909399;
          margin-left: 8px;
        }
      }
    }
  }
}

.certification-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .header-actions {
      display: flex;
      gap: 12px;
    }
  }

  .certification-form {
    .form-section {
      margin-bottom: 32px;
      
      .section-title {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 16px;
        font-weight: bold;
        color: #303133;
        margin-bottom: 20px;
        padding-left: 12px;
        border-left: 4px solid #409eff;
        
        .el-icon {
          font-size: 18px;
        }
      }
    }
  }
  
  .upload-tips {
    margin-bottom: 20px;
  }
  
  .certification-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 100%;
    height: 200px;
    
    &:hover {
      border-color: #409eff;
    }
    
    .upload-content {
      width: 100%;
      height: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      
      .uploader-icon {
        font-size: 28px;
        color: #8c939d;
        margin-bottom: 8px;
      }
      
      .upload-tip {
        font-size: 14px;
        color: #303133;
        margin-bottom: 4px;
      }
      
      .upload-desc {
        font-size: 12px;
        color: #909399;
      }
      
      .uploaded-image {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
  }
  
  .certification-status {
    margin-top: 32px;
    padding: 32px;
    background-color: #f5f7fa;
    border-radius: 4px;
  }

  /* 营业执照展示样式 */
  .license-display {
    display: flex;
    gap: 20px;
    padding: 20px;
    background: #f8fafc;
    border-radius: 8px;
    border: 1px solid #e5e7eb;

    .license-info {
      flex: 1;

      .info-row {
        display: flex;
        gap: 30px;
        margin-bottom: 15px;

        &:last-child {
          margin-bottom: 0;
        }
      }

      .info-item {
        display: flex;
        align-items: center;

        .label {
          font-size: 14px;
          color: #6b7280;
          margin-right: 8px;
          min-width: 80px;
        }

        .value {
          font-size: 14px;
          color: #1f2937;
          font-weight: 500;
        }
      }
    }

    .license-image-display {
      width: 200px;
      text-align: center;

      .license-preview {
        width: 100%;
        height: 120px;
        object-fit: cover;
        border-radius: 6px;
        border: 1px solid #e5e7eb;
      }

      .image-status {
        margin-top: 8px;
      }
    }
  }

  .certification-note {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-top: 15px;
    padding: 12px;
    background: #eff6ff;
    border-radius: 6px;
    border-left: 4px solid #3b82f6;

    .el-icon {
      color: #3b82f6;
      font-size: 16px;
    }

    span {
      font-size: 13px;
      color: #1e40af;
    }
  }

  /* 退店申请样式 */
  .quit-store-section {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    padding: 20px;
    background: #fef2f2;
    border-radius: 8px;
    border: 1px solid #fecaca;

    .quit-info {
      display: flex;
      gap: 15px;
      flex: 1;

      .warning-icon {
        color: #dc2626;
        font-size: 24px;
        margin-top: 2px;
      }

      .quit-content {
        h4 {
          margin: 0 0 8px 0;
          color: #dc2626;
          font-size: 16px;
        }

        p {
          margin: 0 0 12px 0;
          color: #7f1d1d;
          font-size: 14px;
          line-height: 1.5;
        }

        .quit-conditions {
          margin: 0;
          padding-left: 20px;
          color: #7f1d1d;

          li {
            margin-bottom: 6px;
            font-size: 13px;
            line-height: 1.4;
          }
        }
      }
    }

    .quit-actions {
      margin-left: 20px;
    }
  }
}

/* 退店对话框样式 */
.quit-dialog-content {
  .quit-warning {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 20px;
    padding: 15px;
    background: #fef2f2;
    border-radius: 8px;
    border-left: 4px solid #dc2626;

    .warning-icon {
      color: #dc2626;
      font-size: 24px;
    }

    h3 {
      margin: 0;
      color: #dc2626;
      font-size: 16px;
    }
  }

  .quit-checklist {
    margin-bottom: 20px;

    h4 {
      margin: 0 0 15px 0;
      color: #1f2937;
      font-size: 14px;
    }

    .checklist-item {
      margin-bottom: 12px;
      padding: 8px 0;
    }
  }

  .quit-notice {
    margin-top: 20px;

    :deep(.el-alert__content) {
      p {
        margin: 3px 0;
        font-size: 13px;
        line-height: 1.4;
      }
    }
  }
}

.mt-2 {
  margin-top: 8px;
}

/* 银行卡管理样式 */
.bank-card {
  margin-top: 20px;

  .bank-list {
    .bank-cards {
      .bank-card-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 16px;
        border: 1px solid #e4e7ed;
        border-radius: 8px;
        margin-bottom: 12px;
        transition: all 0.3s;

        &:hover {
          border-color: #409eff;
          box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
        }

        &.default-card {
          border-color: #67c23a;
          background: #f0f9ff;
        }

        &:last-child {
          margin-bottom: 0;
        }

        .card-info {
          display: flex;
          align-items: center;
          gap: 12px;

          .card-icon {
            .el-icon {
              font-size: 24px;
              color: #409eff;
            }
          }

          .card-details {
            .card-number {
              font-size: 16px;
              font-weight: 600;
              color: #303133;
              margin-bottom: 4px;
              font-family: 'Courier New', monospace;
              letter-spacing: 1px;
            }

            .card-bank {
              font-size: 14px;
              color: #606266;
              margin-bottom: 4px;
              font-weight: 500;
            }

            .card-holder {
              font-size: 13px;
              color: #909399;
              margin-bottom: 4px;
            }

            .card-type {
              font-size: 12px;
              color: #909399;
              background: #f5f7fa;
              padding: 2px 6px;
              border-radius: 4px;
              display: inline-block;
            }
          }

          .card-status {
            margin-left: 12px;

            .el-tag {
              margin-right: 4px;
            }
          }
        }

        .card-actions {
          display: flex;
          gap: 8px;
        }
      }
    }

    .no-bank-cards {
      text-align: center;
      padding: 40px 20px;
    }
  }
}

/* 商家资质信息样式 */
.qualification-card {
  margin-bottom: 20px;

  .qualification-info {
    .info-item {
      display: flex;
      margin-bottom: 12px;

      .label {
        width: 100px;
        color: #606266;
        font-weight: 500;
      }

      .value {
        color: #303133;
        flex: 1;
      }

      .service-types-display {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;

        .service-tag {
          margin: 0;
        }
      }
    }
  }
}

/* 安全设置样式优化 */
.security-card {
  .security-list {
    .security-item {
      .item-info {
        .item-details {
          display: flex;
          flex-direction: column;
          gap: 4px;

          .item-label {
            font-weight: 500;
            color: #303133;
          }

          .item-value {
            color: #909399;
            font-size: 13px;
          }

          .item-status {
            color: #67c23a;
            font-size: 13px;
          }
        }
      }
    }
  }
}

/* 响应式布局优化 */
@media screen and (max-width: 1200px) {
  .el-col-8 {
    width: 100%;
  }

  .el-col-16 {
    width: 100%;
  }

  .el-col-12 {
    width: 100%;
  }
}
</style>